package ajaxjs.admin.entry;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
public class fixPut {
	/**
	 * servlet获取put提交的参数
	 * http://my.oschina.net/dxqr/blog/138444
	 * @return
	 */
	public static String getRawParams(HttpServletRequest request){
//		if(request.getMethod() == "PUT"){
			StringBuilder str = new StringBuilder();
			
			String s = null, params = "";

			try {
				java.io.BufferedReader br = new java.io.BufferedReader(
						new java.io.InputStreamReader(request.getInputStream(), "UTF-8")
				);

				while((s = br.readLine()) != null) {
//					System.out.println(s);
					str.append(s);
				}
			} catch (java.io.IOException e) {
				e.printStackTrace();
			}
			
			params = str.toString();
			
			return params;
//		}else{
//			System.out.println("你的不是 PUT 请求，无须该补丁啊");
//			return null;
//		}
	}
	public static Map<String, String> getPutRequest(HttpServletRequest request){
		String params = getRawParams(request);
		String[] arr = params.split("&");
		
		Map<String, String> hash = new HashMap<String, String>();
		
		for(int i = 0, j = arr.length; i < j; i++){
			String str = arr[i];
			int index = str.indexOf('=');
			String key = str.substring(0, index);
			String value = str.substring(index + 1);
			
//			System.out.println(key + ":::" + value);
			
			try {
				hash.put(key, URLDecoder.decode(value, "UTF-8"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		
		return hash;
	}
	
	
	public static String getPutRequest(HttpServletRequest request, String key){
		return getParameter(getRawParams(request), key);
	}
	private static String getParameter(String url, String paramName) throws ArrayIndexOutOfBoundsException {
	    Pattern pattern = Pattern.compile(paramName + "=[^&]*"); // regex for "paramName='anything unless is &'"
	    Matcher matcher = pattern.matcher(url);
	    matcher.find();
	    String value = matcher.group().split("=")[1];
	    return value;
	}
}
